﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Handday.Erp.Transfer.Services;
using System.Threading.Tasks;
using HandDay.Framework.Common;
using Handday.Erp.Transfer.Models.EightTradingSource;
using System.ComponentModel.DataAnnotations;
using Handday.Erp.Core;
using System;
using Handday.Erp.Transfer.Models;
using System.Linq;

namespace Handday.Erp.Transfer.Controllers
{
    /// <summary>
    /// 8项交易数据控制器
    /// </summary>
    public class EightTradingController : ApiController
    {
        private readonly IEightTradingService _eightTradingService;
        private readonly IBackgroundJobService _backgroundJobService;
        private readonly IPublishCommonService _publishCommonService;
        private readonly IStatisticsCommonService _statisticsCommonService;
        private readonly ICorpService _corpService;

        /// <summary>
        /// ctor
        /// </summary>
        public EightTradingController(
            IEightTradingService eightTradingService,
            IBackgroundJobService backgroundJobService,
            IPublishCommonService publishCommonService,
            IStatisticsCommonService statisticsCommonService,
            ICorpService corpService)
        {
            _eightTradingService = eightTradingService;
            _backgroundJobService = backgroundJobService;
            _publishCommonService = publishCommonService;
            _statisticsCommonService = statisticsCommonService;
            _corpService = corpService;
        }

        /// <summary>
        /// 接收erp8项交易数据
        /// </summary>
        [HttpPost("receive")]
        [DisableFormat]
        public async Task<ErpResultBase> ReceiveAsync([Required, MinLength(1)] List<EightTradingSourceAddDto> list)
        {
            var result = await _eightTradingService.ReceiveAsync(list);
            return ErpResultBase.From(result);
        }

        /// <summary>
        /// 获取最大记账日期
        /// </summary>
        /// <param name="corpId">企业编号</param>
        [HttpGet("get_max_account_time")]
        public async Task<IApiResult<EightTradingAccountTimeDto>> GetMaxAccountTimeAsync(ulong corpId)
        {
            var result = await _eightTradingService.GetMaxAccountTimeAsync(corpId);
            return ApiResult.From(result);
        }

        /// <summary>
        /// 交易数据统计任务
        /// </summary>
        [HttpPost("statistic_task")]
        public async Task<IApiResult> StatisticTaskAsync()
        {
            if (!DateTimeOffset.TryParse(Request.Query["time"], out var time))
            {
                time = DateTimeOffset.Now;
            }

            var corpIdList = (await _corpService.GetListAsync(Enum.ErpFeatureTypeEnum.EightTrading)).Select(m => m.CorpId).ToList();
            if (ulong.TryParse(Request.Query["corpId"], out var reqCorpId))
            {
                corpIdList.Clear();
                corpIdList.Add(reqCorpId);
            }

            foreach (var corpId in corpIdList)
            {
                _backgroundJobService.Transfer<IStatisticsCommonService>(service => service.StatisticsAsync(Enum.ErpFeatureTypeEnum.EightTrading, corpId, time), $"{nameof(EightTradingController)}_statistic_task_{corpId}");
            }

            return ApiResult.Succeed(null);
        }

        /// <summary>
        /// 推送数据任务
        /// </summary>
        /// <returns></returns>
        [HttpPost("publish_task")]
        public async Task<IApiResult> PublishDataTaskAsync()
        {
            if (!DateTimeOffset.TryParse(Request.Query["time"], out var time))
            {
                time = DateTimeOffset.Now;
            }

            var corpIdList = (await _corpService.GetListAsync(Enum.ErpFeatureTypeEnum.EightTrading)).Select(m => m.CorpId).ToList();
            if (ulong.TryParse(Request.Query["corpId"], out var reqCorpId))
            {
                corpIdList.Clear();
                corpIdList.Add(reqCorpId);
            }

            foreach (var corpId in corpIdList)
            {
                _backgroundJobService.Transfer<IPublishCommonService>(service => service.PublishAsync(Enum.ErpFeatureTypeEnum.EightTrading, corpId, time), $"{nameof(EightTradingController)}_publish_task_{corpId}");
            }

            return ApiResult.Succeed(null);
        }

        /// <summary>
        /// 清除数据
        /// </summary>
        [HttpPost("clear")]
        public async Task<IApiResult> ClearAsync(DateTimeOffset? time)
        {
            var result = await _eightTradingService.ClearAsync(time);
            return ApiResult.Succeed(null);
        }

        /// <summary>
        /// 初始数据表
        /// </summary>
        /// <param name="corpId">企业编号</param>
        [HttpPost("init_table")]
        public async Task<IApiResult> InitTableAsync(ulong corpId)
        {
            await _eightTradingService.InitTableAsync(corpId);
            return ApiResult.Succeed(null);
        }

        /// <summary>
        /// 源数据列表
        /// </summary>
        [HttpPost("pagelist")]
        public async Task<IApiResult<List<EightTradingSourceDto>>> PageListAsync(EightTradingSourceRequestDto request)
        {
            var list = await _eightTradingService.PageListAsync(request);
            return ApiResult.Succeed(list);
        }
    }
}